import router from "@/router";
import axios from "axios";
import { ElMessage } from 'element-plus';

// 使用由库提供的配置的默认值来创建实例
// 此时超时配置的默认值是 `0`
// 覆写库的超时默认值
// 现在，在超时前，所有请求都会等待 5.0 秒
const instance = axios.create({
	baseURL: '/api',
	timeout: 5000,
});

// 添加请求拦截器
instance.interceptors.request.use(
	function (config) {
		let token = sessionStorage.getItem('token')
		if (token) {
			config.headers!.token = token
		}
		return config;
	},
	function (error) {
		// 对请求错误做些什么
		return Promise.reject(error);
	}
);

//添加响应拦截器
instance.interceptors.response.use(
	function (response) {
		// 对响应数据做点什么
		if (response.data.code !== 200) {
			if (response.data.msg == 'NOT LOGIN') {
				ElMessage.warning('请先登录');
				sessionStorage.removeItem('token')
				sessionStorage.removeItem('currentUserId')
				router.push('/')
				location.reload()
			} else {
				ElMessage.error(response.data.msg);
			}
		}
		return response.data;
	},
	function (error) {
		console.log(error);

		// 对响应错误做点什么
		if (error.code == 'ECONNABORTED') {
			// 请求超时
			ElMessage.error("请求超时，请检查网络连接！");
		}

		return Promise.reject(error);
	}
);

const get = (url: string, data: any) => {
	return new Promise((resolve, reject) => {
		instance
			.get(url, { params: data })
			.then((res) => {
				resolve(res);
			})
			.catch((err) => {
				reject(err);
			});
	});
};
const deleter = (url: string, data: any) => {
	return new Promise((resolve, reject) => {
		instance
			.delete(url, { params: data })
			.then((res) => {
				resolve(res);
			})
			.catch((err) => {
				reject(err);
			});
	});
};
const post = (url: string, data: any) => {
	return new Promise((resolve, reject) => {
		instance
			.post(url, data)
			.then((res) => {
				resolve(res);
			})
			.catch((err) => {
				reject(err);
			});
	});
};
const put = (url: string, data: any) => {
	return new Promise((resolve, reject) => {
		instance
			.put(url, data)
			.then((res) => {
				resolve(res);
			})
			.catch((err) => {
				reject(err);
			});
	});
};
export { get, post, deleter, put };